package bg.uni_sofia.conf_manager.beans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import bg.uni_sofia.conf_manager.model.Company;

/**
 * Session Bean implementation class CompanyBean
 */
@Stateless
@Path("/company")
public class CompanyBean {

	@PersistenceContext
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public CompanyBean() {
		// TODO Auto-generated constructor stub
	}

	@POST
	@Consumes("application/json")
	public Company addCompany(Company newCompany) {
		if (newCompany != null) {
			Company company = getCompanyByName(newCompany.getCompanyName());
			if (company == null) {
				em.persist(newCompany);
				return newCompany;
			}
		}
		return null;
	}

	@GET
	@Produces("application/json")
	public List<Company> getAllCompanies() {
		return em.createNamedQuery("getAllCompanies", Company.class)
				.getResultList();
	}

	@GET
	@Path("/{id}")
	@Produces("application/json")
	public Company getCompanyById(@PathParam("id") long id) {
		TypedQuery<Company> query = em.createNamedQuery("getCompanyById",
				Company.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	@GET
	@Path("/{name}")
	@Produces("application/json")
	public Company getCompanyByName(@PathParam("name") String name) {
		TypedQuery<Company> query = em.createNamedQuery("getCompanyByName",
				Company.class);
		query.setParameter("companyName", name);
		if (query.getResultList().size() > 0) {
			return query.getResultList().get(0);
		} else {
			return null;
		}
	}

}
